package com.wnxy.be_emp_manager.config;


import com.wnxy.be_emp_manager.utils.MyAuthentication;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;

import javax.servlet.Filter;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @PackgeName: com.yeheng.homework.config
 * @ClassName: ShiroConfig
 * @Author: YH
 * Date: 2021/1/16 23:25
 * project name: homework
 * @Version:
 * @Description:
 */
//@Configuration
public class ShiroConfig {

    @Bean
    public HashedCredentialsMatcher matcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashIterations(1024);
        matcher.setHashAlgorithmName("MD5");
        return matcher;
    }

    @Bean
    public Realm realm(DataSource source, HashedCredentialsMatcher matcher){
        JdbcRealm realm = new JdbcRealm();
        realm.setDataSource(source);
        realm.setCredentialsMatcher(matcher);
        realm.setSaltStyle(JdbcRealm.SaltStyle.COLUMN);
        realm.setPermissionsLookupEnabled(true);
        realm.setAuthenticationQuery("SELECT password,salt FROM users WHERE username = ?");
        realm.setUserRolesQuery("SELECT rname FROM users LEFT JOIN users_roles ON users.uid = users_roles.uid INNER JOIN roles ON users_roles.rid = roles.rid WHERE username = ?");
        realm.setPermissionsQuery("SELECT pname FROM roles a INNER JOIN roles_permissions b ON a.rid = b.rid INNER JOIN permissions c ON c.pid = b.pid WHERE rname = ?");
        return realm;
    }


    @Bean
    public SecurityManager manager(Realm realm){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(realm);
        return manager;
    }


    @Bean
    public ShiroFilterFactoryBean ssfb(SecurityManager manager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(manager);
        Map<String, Filter> filters = factoryBean.getFilters();
        filters.put("authc", new MyAuthentication());
        Map<String, String> map = new HashMap<>();
//        map.put("/**/login","anon");
//        map.put("/logout","logout");
//        map.put("/**","authc");
        factoryBean.setFilterChainDefinitionMap(map);
        return factoryBean;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor advisor(SecurityManager manager){
        AuthorizationAttributeSourceAdvisor sourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        sourceAdvisor.setSecurityManager(manager);
        return sourceAdvisor;
    }
}
